/**
 * 
 */
package com.bible.fire.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.baidu.mapapi.map.LocationData;
import com.bible.fire.local.AppContext;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;


/**
 * @author zhangyp
 *
 */
public class AndroidUtil {
	
	private static final String TAG = AndroidUtil.class.getSimpleName();
	
	//对全局的变量进行操作
	public static boolean setAttribute(String key, Object value){
		return ((AppContext)AppContext.getContext()).setAttribute(key, value);
	}
	
	public static Object getAttribute( String key ){
		return ((AppContext)AppContext.getContext()).getAttribute(key);
	}
	
	public static boolean removeAttribute( String key ){
		return ((AppContext)AppContext.getContext()).removeAttribute(key);
	}
	
	public static boolean clearAttribute(){
		return ((AppContext)AppContext.getContext()).clearAttribute();
	}
    
	/**
	 * 检查存储卡是否插入
	 * @return
	 */
	public static boolean isHasSdcard(){  
	   return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED );  
	}  
	
	/**
	 * wifi打开时获取mac地址
	 * @param activity
	 * @return
	 */
	public static String getMacAddress(){
		try {
			WifiManager wifi = (WifiManager) AppContext.getContext().getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo(); 
			return  info.getMacAddress();
		 }catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "", e);
		 }
		 return "";
	}
	
	 public static String getIpAddress(){     
        try {     
            for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){     
                NetworkInterface intf = en.nextElement();     
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){     
                    InetAddress inetAddress = enumIpAddr.nextElement();     
                    if (!inetAddress.isLoopbackAddress()) {     
                        return inetAddress.getHostAddress().toString();     
                    }     
                }     
            }     
        } catch (SocketException ex) {     
            Log.e("WifiPreference IpAddress", ex.toString());     
        }     
        return "";     
    }  
	 
	 /**
	  * 获得本机电话号码
	  * @return
	  * @deprecated
	  */
	 public static String getTelNumber(){
		 TelephonyManager telMgr = (TelephonyManager)AppContext.getContext().getSystemService(Context.TELEPHONY_SERVICE);
		 return telMgr.getLine1Number();
	 }
	 
	 
	 
	 /**
	  * 获取SIM卡的唯一识别码
	  * @return
	  */
	 public static String getIMSI(){
		 try {
			 TelephonyManager telMgr = (TelephonyManager)AppContext.getContext().getSystemService(Context.TELEPHONY_SERVICE);
			 return telMgr.getSubscriberId();
		 }catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "", e);
		 }
		 return "";
	 }
	 
	 /**
	  * 获取设备唯一识别号码(仅针对有通话功能的设备有效)
	  * @return
	  */
	 public static String getDeviceId(){
		 try {
			 TelephonyManager telMgr = (TelephonyManager)AppContext.getContext().getSystemService(Context.TELEPHONY_SERVICE);
			 return telMgr.getDeviceId();
		 }catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "", e);
		 }
		 return "";
	 }

	 public static String getSerialNumber(){
		 return android.os.Build.SERIAL;
	 }
	 
	 /**
	  * 获取当前程序的版本号
	  * @return
	  */
	 public static String getVersion(){
		 String version = "";
		 try{
			 Context context = AppContext.getContext();
			 PackageManager manager = context.getPackageManager();
			 PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			 version = info.versionName;
		 }catch(Exception e){
			 Log.d( TAG, "get version error..." );
		 }		 
		 return version;
	 }
	 
	 /**
	  * 判断GPS是否开启
	  * @return
	  */
	 public static boolean isGpsOpen(){
		 try {
			 LocationManager lm = (LocationManager) AppContext.getContext().getSystemService(Context.LOCATION_SERVICE);
			 return lm.isProviderEnabled( LocationManager.GPS_PROVIDER );
		 }catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "", e);
		 }
		 return false;
	 }
	 
	 /**
	  * 网络是否可用
	  * @return
	  */
	 public static boolean isNetworkAvailable(){
		 try {
			 ConnectivityManager connectivity = (ConnectivityManager)AppContext.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
			 if( connectivity != null ){
				NetworkInfo info =  connectivity.getActiveNetworkInfo();
				if( info != null && info.isAvailable() && info.isConnected() && info.getState() == NetworkInfo.State.CONNECTED ){
					return true;
				}
			 }
		 }catch (Exception e) {
			Log.e(TAG, "is network available", e);
		 }		 
		 return false;
	 }
	 
	 /**
	  * 通过GPS或google的网络地图来获取当前位置
	  * @return
	  */
	 public static double[] getCurrentLocation(){
		 double[] postions = null;
		 LocationData locData = (LocationData)getAttribute("locationData");
		 if( locData != null ){
			 postions = new double[]{ locData.latitude, locData.longitude };
			 return postions;
		 }
		 try {
			 LocationManager lm = (LocationManager) AppContext.getContext().getSystemService(Context.LOCATION_SERVICE);
			 boolean isFirstOpen = isGpsOpen();
			 if( !isFirstOpen ){
				 lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
			 }
			 //上面通过代码来开启gps可能无效
			 boolean GPS_Status = isGpsOpen();
			 if( GPS_Status ){
				 //通过gps获取位置
				 //Location location = lm.getLastKnownLocation( LocationManager.GPS_PROVIDER );
				 Criteria criteria = new Criteria();  
		         criteria.setAccuracy(Criteria.ACCURACY_FINE);  
		         criteria.setAltitudeRequired(false);  
		         criteria.setBearingRequired(false);  
		         criteria.setCostAllowed(true);  
		         criteria.setPowerRequirement(Criteria.POWER_LOW);
		         String provider = lm.getBestProvider(criteria, true);
		         Location location = lm.getLastKnownLocation( provider );
		         //有的机器不支持最佳位置,则指定位置
		         if( location == null ){
		        	 location = lm.getLastKnownLocation( LocationManager.GPS_PROVIDER );
		         }
				 if( location != null ){
					 postions = new double[]{location.getLatitude(),location.getLongitude()};	 
				 }
				 //如果开始gps是关闭状态，则获取位置之后应该关掉gps
				 if( !isFirstOpen ){
					 lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, false );
				 }
			 }
			 if( postions == null && lm.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ){
				 //通过网络获取位置
				 Location location = lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
				 if( location != null ){
					 postions = new double[]{location.getLatitude(),location.getLongitude()};	 
				 }
			 }			 
		 }catch (Exception e) {
			 e.printStackTrace();
			 Log.e(TAG, "", e);
		 }
		 return postions;
	 }
	 
	 


}
